﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CueSheetLibrary;
using CueMounter.DokanStructure;
using Alphaleonis.Win32.Filesystem;
using FileNotFoundException = System.IO.FileNotFoundException;

namespace CueMounter {
	class DokanCueSheetDirectory : DokanDirectory {
		CueSheet CueSheet;
		DokanCueSheetFile[] CueFiles;
		DokanFile[] files;

		public DokanCueSheetDirectory(string cueFile) {
			Name = Path.GetFileNameWithoutExtension(cueFile);

			CueSheet = new CueSheet(cueFile);
			if(!File.Exists(CueSheet.Filename)) {
				throw new FileNotFoundException("Cue target doesn't exist");
			}

			CueFiles = new DokanCueSheetFile[CueSheet.Tracks.Length];
			for(int i = 0; i < CueSheet.Tracks.Length; ++i) {
				CueFiles[i] = new DokanCueSheetFile(CueSheet, i);
			}

			List<DokanFile> files = new List<DokanFile>();
			for(int i = 0; i < CueFiles.Length; ++i) {
				files.Add(new DokanCachedReadFile(CueFiles[i], 1 * 1024 * 1024));
			}

			files.Add(new DokanReadOnlyTextFile("Info.txt", GetInfoString()));

			this.files = files.ToArray();
		}

		private string GetProperTimeSpan(TimeSpan span) {
			double totalMinutes = span.TotalMinutes;
			int minutes = (int)Math.Floor(totalMinutes);
			totalMinutes -= minutes;
			int seconds = (int)Math.Floor(totalMinutes * 60);
			return minutes.ToString("00") + ":" + seconds.ToString("00");
		}

		private string GetInfoString() {
			StringBuilder infoFile = new StringBuilder();
			infoFile.AppendLine("Performer: " + CueSheet.Performer);
			infoFile.AppendLine("Title: " + CueSheet.Title);
			infoFile.AppendLine();
			infoFile.AppendLine("Tracks:");
			for(int i = 0; i < CueSheet.Tracks.Length; ++i) {
				var track = CueSheet.Tracks[i];
				infoFile.AppendLine("  " + (i + 1).ToString("00") + ". " + track.Title +
					" (" + GetProperTimeSpan(CueFiles[i].TrackLength) + ")"
					+ " [" + GetProperTimeSpan(CueFiles[i].TrackStart) + " -> " + GetProperTimeSpan(CueFiles[i].TrackStart.Add(CueFiles[i].TrackLength)) + "]"
					);
			}
			return infoFile.ToString();
		}

		public override void Dispose() {
			foreach(var file in CueFiles) {
				file.Dispose();
			}
			CueSheet = null;
			CueFiles = null;
			files = null;
		}

		public override DokanFile[] Files {
			get {
				return files;
			}
		}
	}
}
